<!--
<template>
  <div >
    UserId：<input v-model="userid" placeholder="Enter User ID">
    <button @click="a">Open</button>
    <button @click="closeWebSocket">Close</button>

    <br/>

    消息：<input v-model="messageText" type="text"/>
    <button @click="send">Send</button><br/>
    To：<span>{{ to }}</span>
    <div v-html="userListHtml"></div>

    <br/>

    <div v-html="messages"></div>
  </div>
</template>
<script>
export default {
  data(){
    return {
      websocket: null,
      target: "ws://localhost:81/message/websocket/",
      userid: '',
      messageText: '',
      to: '',
      messages: '',
      userListHtml: ''
    }
  },
  methods:{
      a() {
        this.target = "http://localhost:2008/websocket/";
        var userid = this.userid;
        if (userid === '') {
          this.target += '匿名';
        } else {
          this.target += userid;
        }
        //判断当前浏览器是否支持WebSocket
        if ('MozWebSocket' in window) {
          this.websocket = new MozWebSocket(this.target);
        } else if ('WebSocket' in window) {
          this.websocket = new WebSocket(this.target);
        } else {
          alert('Not support websocket');
          return;
        }

        //连接成功建立的回调方法
        this.websocket.onopen = () => {
          this.setMessageInnerHTML("连接成功");
        };

        //连接发生错误的回调方法
        this.websocket.onerror = () => {
          this.setMessageInnerHTML("连接失败");
        };

        //接收到消息的回调方法
        this.websocket.onmessage = (event) => {
          var msg = event.data;
          if (msg.startsWith("users:")) {
            this.setUsersList(msg.substring(6));
          } else {
            this.setMessageInnerHTML(msg);
          }
        };

        //连接关闭的回调方法
        this.websocket.onclose = () => {
          this.setMessageInnerHTML("连接关闭");
        };
      },
      setUsersList(userList) {
        var users = userList.split(",");
        var html = "";
        for (var i = 0; i < users.length; i++) {
          html += `<a href='javascript:void(0)' @click="toUser('${users[i]}')">${users[i]}</a><br/>`;
        }
        this.userListHtml = html;
      },
      setMessageInnerHTML(innerHTML) {
        this.messages += innerHTML + '<br/>';
      },
      closeWebSocket() {
        if (this.websocket) {
          this.websocket.close();
        }
      },
      toUser(userid) {
        this.to = userid;
      },
      send() {
        var message = this.messageText;
        var to = this.to;
        if (to !== null && to !== '') {
          this.websocket.send(message + '#' + to);
        } else {
          this.websocket.send(message);
        }
      }
    ,
    beforeDestroy() {
      if (this.websocket) {
        this.websocket.close();
      }
    }
  }
}

</script>
-->
